//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package utils

import (
	"archive/zip"
	"bytes"
	"io/ioutil"
	"strings"
)

func IsEpubFile(data []byte) bool {
	r := bytes.NewReader(data)
	zr, err := zip.NewReader(r, r.Size())
	if err != nil {
		return false
	}

	hasMeta := false
	hasData := false
	hasMime := false
	for _, f := range zr.File {
		if f.FileInfo().IsDir() {
			if f.Name == "META-INF" {
				hasMeta = true
			} else if f.Name == "OEBPS" {
				hasData = true
			}
		} else {
			if f.Name == "mimetype" {
				zf, err := f.Open()
				if err == nil {
					defer zf.Close()
					mimeData, err := ioutil.ReadAll(zf)
					if err == nil && strings.Contains(string(mimeData), "epub") {
						hasMime = true
					}
				}
			}
		}
	}
	return hasMeta && hasData && hasMime
}
